<!doctype html>



  


<html class="theme-next pisces use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Hexo, NexT" />





  <link rel="alternate" href="/atom.xml" title="liujinlongxa的技术博客" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="原文地址：MVVM Tutorial with ReactiveCocoa: Part 2/2

MVVM作为一种UI设计模式，正在成为一种非常流行的MVC模式的替代方案。
在MVVM系列教程的第一部分，你已经了解了ReactiveCocoa是如何将ViewModels和他们各自的的View绑定起来的。

下面是你创建的应用，一个搜索Flickr的APP。

在 MVVM系列教程的第二部分以及最后">
<meta property="og:type" content="article">
<meta property="og:title" content="【翻译】MVVM Tutorial with ReactiveCocoa Part 2">
<meta property="og:url" content="http://yoursite.com/2016/05/09/MVVMTutorialwithReactiveCocoaPart2(翻译)/index.html">
<meta property="og:site_name" content="liujinlongxa的技术博客">
<meta property="og:description" content="原文地址：MVVM Tutorial with ReactiveCocoa: Part 2/2

MVVM作为一种UI设计模式，正在成为一种非常流行的MVC模式的替代方案。
在MVVM系列教程的第一部分，你已经了解了ReactiveCocoa是如何将ViewModels和他们各自的的View绑定起来的。

下面是你创建的应用，一个搜索Flickr的APP。

在 MVVM系列教程的第二部分以及最后">
<meta property="og:image" content="https://cdn5.raywenderlich.com/wp-content/uploads/2014/06/MVVMReactiveCocoa-700x121.png">
<meta property="og:image" content="https://cdn3.raywenderlich.com/wp-content/uploads/2014/06/FinishedApp-671x500.png">
<meta property="og:image" content="https://cdn4.raywenderlich.com/wp-content/uploads/2014/06/BlankView-281x500.png">
<meta property="og:image" content="https://cdn2.raywenderlich.com/wp-content/uploads/2014/06/PopulatedTable-281x500.png">
<meta property="og:image" content="http://www.raywenderlich.com/wp-content/uploads/2014/06/UsingTheBindingHelper.png">
<meta property="og:image" content="http://www.raywenderlich.com/wp-content/uploads/2014/06/ParallaxAnimation.gif">
<meta property="og:updated_time" content="2016-07-01T12:43:36.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【翻译】MVVM Tutorial with ReactiveCocoa Part 2">
<meta name="twitter:description" content="原文地址：MVVM Tutorial with ReactiveCocoa: Part 2/2

MVVM作为一种UI设计模式，正在成为一种非常流行的MVC模式的替代方案。
在MVVM系列教程的第一部分，你已经了解了ReactiveCocoa是如何将ViewModels和他们各自的的View绑定起来的。

下面是你创建的应用，一个搜索Flickr的APP。

在 MVVM系列教程的第二部分以及最后">
<meta name="twitter:image" content="https://cdn5.raywenderlich.com/wp-content/uploads/2014/06/MVVMReactiveCocoa-700x121.png">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://yoursite.com/2016/05/09/MVVMTutorialwithReactiveCocoaPart2(翻译)/"/>

  <title> 【翻译】MVVM Tutorial with ReactiveCocoa Part 2 | liujinlongxa的技术博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">liujinlongxa的技术博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                【翻译】MVVM Tutorial with ReactiveCocoa Part 2
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-05-09T00:00:00+08:00" content="2016-05-09">
              2016-05-09
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/iOS开发/" itemprop="url" rel="index">
                    <span itemprop="name">iOS开发</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/2016/05/09/MVVMTutorialwithReactiveCocoaPart2(翻译)/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2016/05/09/MVVMTutorialwithReactiveCocoaPart2(翻译)/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>原文地址：<a href="https://www.raywenderlich.com/74131/mvvm-tutorial-with-reactivecocoa-part-2" target="_blank" rel="external">MVVM Tutorial with ReactiveCocoa: Part 2/2</a></p>
<hr>
<p>MVVM作为一种UI设计模式，正在成为一种非常流行的MVC模式的替代方案。</p>
<p>在MVVM系列教程的第一部分，你已经了解了ReactiveCocoa是如何将ViewModels和他们各自的的View绑定起来的。</p>
<p><img src="https://cdn5.raywenderlich.com/wp-content/uploads/2014/06/MVVMReactiveCocoa-700x121.png" alt="1"></p>
<p>下面是你创建的应用，一个搜索Flickr的APP。</p>
<p><img src="https://cdn3.raywenderlich.com/wp-content/uploads/2014/06/FinishedApp-671x500.png" alt="2"></p>
<p>在 MVVM系列教程的第二部分以及最后一部分，你讲学会如果从应用程序的ViewModel中控制ViewController的导航。</p>
<p>截止目前，你所开发的应用可以通过一个简单的字符串搜索Flickr，如果你需要当前的项目，可以从<a href="http://www.raywenderlich.com/wp-content/uploads/2014/06/FlickrSearchPart1Project1.zip" target="_blank" rel="external">这里</a>下载</p>
<p>使用ReactiveCocoa构建的模型层服务提供搜索结果，对应的ViewModel能够简单地打印出响应结果。</p>
<p>现在，是时候完成跳转到搜索结果界面的任务了。</p>
<h2 id="实现ViewModel导航"><a href="#实现ViewModel导航" class="headerlink" title="实现ViewModel导航"></a>实现ViewModel导航</h2><p>搜索Flickr成功并返回正确的结果后，应用程序应该跳转到一个新的ViewController并显示这些搜索结果。</p>
<p>当前应该程序只有单一的一个ViewModel，即RWTFlickrSearchViewModel类。为了达到预期的效果，你应该再创建一个ViewModel来描述返回的搜索结果视图。</p>
<p>在ViewModel文件夹中一个名为RWTSearchResultsViewModel类，他继承自NSObject。代码如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">@import</span> Foundation;</div><div class="line"><span class="meta">#import <span class="meta-string">"RWTViewModelServices.h"</span></span></div><div class="line"><span class="meta">#import <span class="meta-string">"RWTFlickrSearchResults.h"</span></span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">RWTSearchResultsViewModel</span> : <span class="title">NSObject</span></span></div><div class="line"></div><div class="line">- (<span class="keyword">instancetype</span>)initWithSearchResults:(RWTFlickrSearchResults *)results services:(<span class="keyword">id</span>&lt;RWTViewModelServices&gt;)services;</div><div class="line"></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">strong</span>, <span class="keyword">nonatomic</span>) <span class="built_in">NSString</span> *title;</div><div class="line"><span class="keyword">@property</span> (<span class="keyword">strong</span>, <span class="keyword">nonatomic</span>) <span class="built_in">NSArray</span> *searchResults;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
<p>上面的代码中添加了一些属性用于描述搜索结果视图，并且声明了一个包含一个RWTFlickrSearchResults参数（返回模型层的服务）的构造方法。</p>
<p>打开RWTSearchResultsViewModel.m实现以下代码：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">instancetype</span>)initWithSearchResults:(RWTFlickrSearchResults *)results services:(<span class="keyword">id</span>&lt;RWTViewModelServices&gt;)services &#123;</div><div class="line">  <span class="keyword">if</span> (<span class="keyword">self</span> = [<span class="keyword">super</span> init]) &#123;</div><div class="line">    _title = results.searchString;</div><div class="line">    _searchResults = results.photos;</div><div class="line">  &#125;</div><div class="line">  <span class="keyword">return</span> <span class="keyword">self</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这样RWTSearchResultsViewModel就完成了。</p>
<p>回忆第一部分的内容，ViewModel应该在对应的View创建之前就已经创建好了，下面就是要完成各个ViewModel对应了View了。</p>
<p>打开RWTSearchResultsViewController.h文件，导入对应的ViewModel头文件，并且添加一个初始化方法，代码如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"RWTSearchResultsViewModel.h"</span></span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">RWTSearchResultsViewController</span> : <span class="title">UIViewController</span></span></div><div class="line"></div><div class="line">- (<span class="keyword">instancetype</span>)initWithViewModel:(RWTSearchResultsViewModel *)viewModel;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
<p>打开RWTSearchResultsViewController.m文件，并且在顶部的类扩展中添加一个私有属性，如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">@property</span> (<span class="keyword">strong</span>, <span class="keyword">nonatomic</span>) RWTSearchResultsViewModel *viewModel;</div></pre></td></tr></table></figure>
<p>进一步完成初始化方法的实现，如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">instancetype</span>)initWithViewModel:(RWTSearchResultsViewModel *)viewModel &#123;</div><div class="line">  <span class="keyword">if</span> (<span class="keyword">self</span> = [<span class="keyword">super</span> init]) &#123;</div><div class="line">    _viewModel = viewModel;</div><div class="line">  &#125;</div><div class="line">  <span class="keyword">return</span> <span class="keyword">self</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这一步中，你将关注视图导航是如何工作的。</p>
<p>你的应用程序现在有两个ViewModel，但是这里你将面临一个难题！我该怎么在视图控制器切换的同时也把对应的ViewModel进行切换。</p>
<p>ViewModel不能直接持有View的引用，所以，有什么巧妙的方法可以实现这个呢？</p>
<p>答案已经在RWTViewModelServices协议中展现了。它当前被用来获得一个模型层的引用，你将用这个协议来实现ViewModel的切换。</p>
<p>打开RWTViewModelServices.h并且添加如下方法到协议中去。</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)pushViewModel:(<span class="keyword">id</span>)viewModel;</div></pre></td></tr></table></figure>
<p>从概念上讲，ViewModel层驱动着整个App，这一层的逻辑决定着界面上会显示什么，以及界面之间切换的方式和时机。</p>
<p>这个方法允许ViewModel也像UINavigationController那样可以从一个ViewModel以Push的方法切换到另一个ViewModel。</p>
<p>在实现这个协议之前，你应该先是这个方法在ViewModel层可以工作。</p>
<p>打开RWTFlickrSearchViewModel.m文件并导入新添加的ViewModel。</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"RWTSearchResultsViewModel.h"</span></span></div></pre></td></tr></table></figure>
<p>在同一文件更新executeSearchSignal方法的实现，代码如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">- (RACSignal *)executeSearchSignal &#123;</div><div class="line">  <span class="keyword">return</span> [[[<span class="keyword">self</span>.services getFlickrSearchService]</div><div class="line">    flickrSearchSignal:<span class="keyword">self</span>.searchText]</div><div class="line">    doNext:^(<span class="keyword">id</span> result) &#123;</div><div class="line">      RWTSearchResultsViewModel *resultsViewModel =</div><div class="line">        [[RWTSearchResultsViewModel alloc] initWithSearchResults:result services:<span class="keyword">self</span>.services];</div><div class="line">      [<span class="keyword">self</span>.services pushViewModel:resultsViewModel];</div><div class="line">    &#125;];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>上面的代码在搜索信号执行过程中添加了一个doNext操作，在doNext的block中创建了一个新的ViewModel来展示搜索结果，然后通过ViewModel的services的push操作切换到这个新的ViewModel上。</p>
<p>现在，该更新代码，实现这个协议并达到切换ViewModel同时切换ViewController的效果。为了实现这个效果，我们需要在代码中引用导航控制器。</p>
<p>打开RWTViewModelServicesImpl.h并且添加如下初始化方法：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">instancetype</span>)initWithNavigationController:(<span class="built_in">UINavigationController</span> *)navigationController;</div></pre></td></tr></table></figure>
<p>打开RWTViewModelServicesImpl.m并且添加下面的头文件：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"RWTSearchResultsViewController.h"</span></span></div></pre></td></tr></table></figure>
<p>然后添加一个私有属性：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">@property</span> (<span class="keyword">weak</span>, <span class="keyword">nonatomic</span>) <span class="built_in">UINavigationController</span> *navigationController;</div></pre></td></tr></table></figure>
<p>然后在同一个文件完成方法的实现：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">instancetype</span>)initWithNavigationController:(<span class="built_in">UINavigationController</span> *)navigationController &#123;</div><div class="line">  <span class="keyword">if</span> (<span class="keyword">self</span> = [<span class="keyword">super</span> init]) &#123;</div><div class="line">    _searchService = [RWTFlickrSearchImpl new];</div><div class="line">    _navigationController = navigationController;</div><div class="line">  &#125;</div><div class="line">  <span class="keyword">return</span> <span class="keyword">self</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>上述代码用来把传过来的导航控制器引用记录下来。</p>
<p>最后，添加一个新的方法：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)pushViewModel:(<span class="keyword">id</span>)viewModel &#123;</div><div class="line">  <span class="keyword">id</span> viewController;</div><div class="line"></div><div class="line">  <span class="keyword">if</span> ([viewModel isKindOfClass:RWTSearchResultsViewModel.class]) &#123;</div><div class="line">    viewController = [[RWTSearchResultsViewController alloc] initWithViewModel:viewModel];</div><div class="line">  &#125; <span class="keyword">else</span> &#123;</div><div class="line">    <span class="built_in">NSLog</span>(<span class="string">@"an unknown ViewModel was pushed!"</span>);</div><div class="line">  &#125;</div><div class="line"></div><div class="line">  [<span class="keyword">self</span>.navigationController pushViewController:viewController animated:<span class="literal">YES</span>];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>上述代码会根据ViewModel的类型来判断该显示那个视图。</p>
<p>一般来说，View和ViewModel是一一对应的关系，但是你一定可以举出反例。</p>
<p>最后一步，打开RWTAppDelegate.m，将createInitialViewController方法中创建RWTViewModelServicesImpl的一行改为如下代码：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">self</span>.viewModelServices = [[RWTViewModelServicesImpl alloc] initWithNavigationController:<span class="keyword">self</span>.navigationController];</div></pre></td></tr></table></figure>
<p>编译并运行程序，输入一个搜索关键字然后点击Go，可以观察到应用程序将切换到一个新的View/ViewModel。</p>
<p><img src="https://cdn4.raywenderlich.com/wp-content/uploads/2014/06/BlankView-281x500.png" alt="3"></p>
<p>界面是空白的，别着急，待会你将修复这个问题。</p>
<p>现在，可以庆祝一下，你已经实现了一个含有多个ViewModel并且可以通过ViewModel来切换界面的应用程序了。</p>
<blockquote>
<p>小贴士：John Gossman是一名微软WPF团队的工程师，他创造了MVVM模式。他说测试MVVM的一种方法就是你的应用程序应该脱离UI也可以运行。</p>
<p>你的应用程序通过了这个测试。如果你不确信，可以通过单元测试来执行一个搜索或从一个ViewModel切换到另一个ViewModel。</p>
</blockquote>
<p>现在，你已经有了一个非常纯净的解决方案，下面要开始绑定UI了。</p>
<h2 id="呈现搜索结果列表"><a href="#呈现搜索结果列表" class="headerlink" title="呈现搜索结果列表"></a>呈现搜索结果列表</h2><p>搜索结果视图控制器RWTSearchResultsViewController在nib中定义了一个UITableview，下一步就是讲ViewModel中的内容展现在这个列表中。</p>
<p>打开RWTSearchResultsViewController.m，添加一个类扩展，让他实现UITableViewDataSource协议，如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">RWTSearchResultsViewController</span> () &lt;<span class="title">UITableViewDataSource</span>&gt;</span></div></pre></td></tr></table></figure>
<p>在同一文件中重写viewDidLoad方法，代码如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)viewDidLoad &#123;</div><div class="line">  [<span class="keyword">super</span> viewDidLoad];</div><div class="line"></div><div class="line">  [<span class="keyword">self</span>.searchResultsTable registerClass:<span class="built_in">UITableViewCell</span>.class</div><div class="line">                  forCellReuseIdentifier:<span class="string">@"cell"</span>];</div><div class="line">  <span class="keyword">self</span>.searchResultsTable.dataSource = <span class="keyword">self</span>;</div><div class="line"></div><div class="line">  [<span class="keyword">self</span> bindViewModel];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这些操作会在tableview初始化时执行一次，并绑定ViewModel。请忽略上面的Cell Identifier的硬编码，这个待会会删掉。</p>
<p>然后在同一文件中，添加bindViewModel方法。</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)bindViewModel &#123;</div><div class="line">  <span class="keyword">self</span>.title = <span class="keyword">self</span>.viewModel.title;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>当前并没有添加太多代码。ViewModel有两个属性，一个是标题，另一个是将要展示在列表中的搜索结果的数组。</p>
<p>因此，你该如何把这些搜索结果绑定到Tableview上呢？</p>
<p>ReactiveCocoa可以绑定简单的属性到UIKit上，但是无法处理复杂的Tableview的数据绑定。</p>
<p>不用焦急，还有其他方法。可以使用传统的代理方法实现。</p>
<p>在同一文件中，添加如下两个dataSource的代理方法：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">- (<span class="built_in">NSInteger</span>)tableView:(<span class="built_in">UITableView</span> *)tableView</div><div class="line"> numberOfRowsInSection:(<span class="built_in">NSInteger</span>)section &#123;</div><div class="line">  <span class="keyword">return</span> <span class="keyword">self</span>.viewModel.searchResults.count;</div><div class="line">&#125;</div><div class="line"></div><div class="line">- (<span class="built_in">UITableViewCell</span> *)tableView:(<span class="built_in">UITableView</span> *)tableView</div><div class="line">         cellForRowAtIndexPath:(<span class="built_in">NSIndexPath</span> *)indexPath &#123;</div><div class="line">  <span class="built_in">UITableViewCell</span> *cell = [tableView dequeueReusableCellWithIdentifier:<span class="string">@"cell"</span>];</div><div class="line">  cell.textLabel.text = [<span class="keyword">self</span>.viewModel.searchResults[indexPath.row] title];</div><div class="line">  <span class="keyword">return</span> cell;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>第一个方法用来告诉Tableview搜索结果的个数，第二个方法根据ViewModel返回一个相应的Cell。这就够了，不是吗？</p>
<p>编译并运行程序，就可以看到数据了</p>
<p><img src="https://cdn2.raywenderlich.com/wp-content/uploads/2014/06/PopulatedTable-281x500.png" alt="4"></p>
<h2 id="更好的Tableview数据绑定方法"><a href="#更好的Tableview数据绑定方法" class="headerlink" title="更好的Tableview数据绑定方法"></a>更好的Tableview数据绑定方法</h2><p>这种绑定Tableview数据的方法的缺点就是很快就会使视图控制器的代码变得很大。手动绑定数据的方法看起来也不是很优雅。</p>
<p>这个问题困扰着我，因此我着手解决这个问题。</p>
<p>从理论上讲，ViewModel的搜索结果数据中的每一项自身也是一个与Cell一一对应的ViewModel。在我的一篇最近的<a href="http://www.scottlogic.com/blog/2014/05/11/reactivecocoa-tableview-binding.html" target="_blank" rel="external">博客</a>中，我创建了一个通用的绑定辅助类，叫做CETableViewBindingHelper，这个类允许你使用每一个子ViewModel创建一个视图。这个类可以用来辅助实现datasource协议。</p>
<p>这个CETableViewBindingHelper类的构造方法如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">+ (<span class="keyword">instancetype</span>) bindingHelperForTableView:(<span class="built_in">UITableView</span> *)tableView</div><div class="line">                              sourceSignal:(RACSignal *)source</div><div class="line">                          selectionCommand:(RACCommand *)selection</div><div class="line">                              templateCell:(<span class="built_in">UINib</span> *)templateCellNib;</div></pre></td></tr></table></figure>
<p>你仅仅只需要创建一个辅助类的引用，就可以用来绑定一个View的数组。这个构造方法的参数如下：</p>
<ol>
<li>需要加载ViewModel数组的Tableview</li>
<li>一个source的信号用来监控数据的变化</li>
<li>一个在选中一个Cell后要执行的命令</li>
<li>cell视图的nib</li>
</ol>
<p>nib文件定义的Cell必须实现CEReactiveView协议。</p>
<p>项目中已经包含了一个用于展示搜索结果的Cell视图。打开RWTSearchResultsTableViewCell.h导入协议头文件：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"CEReactiveView.h"</span></span></div></pre></td></tr></table></figure>
<p>实现这个协议：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">RWTSearchResultsTableViewCell</span> : <span class="title">UITableViewCell</span> &lt;<span class="title">CEReactiveView</span>&gt;</span></div></pre></td></tr></table></figure>
<p>下一步就是实现协议方法，打开RWTSearchResultsTableViewCell.m，导入如下内容：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">&lt;SDWebImage/UIImageView+WebCache.h&gt;</span></span></div><div class="line"><span class="meta">#import <span class="meta-string">"RWTFlickrPhoto.h"</span></span></div></pre></td></tr></table></figure>
<p>然后添加如下方法：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)bindViewModel:(<span class="keyword">id</span>)viewModel &#123;</div><div class="line">  RWTFlickrPhoto *photo = viewModel;</div><div class="line">  <span class="keyword">self</span>.titleLabel.text = photo.title;</div><div class="line"></div><div class="line">  <span class="keyword">self</span>.imageThumbnailView.contentMode = <span class="built_in">UIViewContentModeScaleToFill</span>;</div><div class="line"></div><div class="line">  [<span class="keyword">self</span>.imageThumbnailView setImageWithURL:photo.url];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>现在RWTSearchResultsViewModel的searchResults属性包含了一个RWTFlickrPhoto的引用的数组。</p>
<p>你刚刚添加的bindViewModel方法中用到了SDWebImage框架，这是一个非常有用的用来在后台加载图片的第三方框架。</p>
<p>setImageWithURL:是SDWebImage添加的一个UIImageView的分类方法。</p>
<p>最后一步是用绑定辅助类去展示列表。</p>
<p>打开RWTSearchResultsViewController.m导入辅助类头文件：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"CETableViewBindingHelper.h"</span></span></div></pre></td></tr></table></figure>
<p>在同一文件中删除UITableDataSource协议以及实现的两个协议方法。</p>
<p>下一步，在类扩展中添加一个如下的属性：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">@property</span> (<span class="keyword">strong</span>, <span class="keyword">nonatomic</span>) CETableViewBindingHelper *bindingHelper;</div></pre></td></tr></table></figure>
<p>在同一文件中，删除你之前添加的ViewDidload方法中的内容，然后添加如下代码到ViewDidLoad中：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)viewDidLoad &#123;</div><div class="line">  [<span class="keyword">super</span> viewDidLoad];</div><div class="line">  [<span class="keyword">self</span> bindViewModel];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>最后，在bindViewModel方法的最后添加如下代码：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line"><span class="built_in">UINib</span> *nib = [<span class="built_in">UINib</span> nibWithNibName:<span class="string">@"RWTSearchResultsTableViewCell"</span> bundle:<span class="literal">nil</span>];</div><div class="line"></div><div class="line"><span class="keyword">self</span>.bindingHelper =</div><div class="line">  [CETableViewBindingHelper bindingHelperForTableView:<span class="keyword">self</span>.searchResultsTable</div><div class="line">                                         sourceSignal:RACObserve(<span class="keyword">self</span>.viewModel, searchResults)</div><div class="line">                                     selectionCommand:<span class="literal">nil</span></div><div class="line">                                         templateCell:nib];</div></pre></td></tr></table></figure>
<p>上述代码从nib文件中创建了一个UINIb类型的引用，并且创建了一个绑定辅助类的对象。通过观察ViewModel中的searchResults属性来创建一个sourceSignal。</p>
<p>编译并运行，结果如下：</p>
<p><img src="http://www.raywenderlich.com/wp-content/uploads/2014/06/UsingTheBindingHelper.png" alt="5"></p>
<p>这就是一种更加又要的绑定数组到Tableview的方法。</p>
<h2 id="一些UI的个性化"><a href="#一些UI的个性化" class="headerlink" title="一些UI的个性化"></a>一些UI的个性化</h2><p>到目前为止，这篇教程始终重点叫的都是如何根据MVVM模式构建你的应用程序。我想你已经忍不住想添加一些个性化的东西了。</p>
<p>自从iOS7发布后，已经过了1年了，<a href="http://www.beyondkinetic.com/motion-ui-design-principles" target="_blank" rel="external">运动设计</a>获得了更大的知名度，许多设计人员现在倾向于微妙的动画和流体行为。</p>
<p>这一步中，你将在照片上添加一个微妙的视差滚动效果，棒极了。</p>
<p>打开RWTSearchResultsTableViewCell.h添加如下方法：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>) setParallax:(<span class="built_in">CGFloat</span>)value;</div></pre></td></tr></table></figure>
<p>列表视图的每个Cell将使用这个方法来为每个Cell做视觉偏移。</p>
<p>打开 RWTSearchResultsTableViewCell.m 文件添加如下代码：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)setParallax:(<span class="built_in">CGFloat</span>)value &#123;</div><div class="line">  <span class="keyword">self</span>.imageThumbnailView.transform = <span class="built_in">CGAffineTransformMakeTranslation</span>(<span class="number">0</span>, value);</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>打开RWTSearchResultsViewController.m导入如下头文件：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"RWTSearchResultsTableViewCell.h"</span></span></div></pre></td></tr></table></figure>
<p>在同一个文件的类扩展中实现UITableViewDelegate的协议，如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">RWTSearchResultsViewController</span> () &lt;<span class="title">UITableViewDataSource</span>, <span class="title">UITableViewDelegate</span>&gt;</span></div></pre></td></tr></table></figure>
<p>你刚刚添加了一个绑定辅助类，并且把他设置为列表视图的代理，是他可以响应列表中行的选中动作。</p>
<p>在bindViewModel方法中设置绑定辅助类的代理：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">self</span>.bindingHelper.delegate = <span class="keyword">self</span>;</div></pre></td></tr></table></figure>
<p>在同一文件中添加scrollViewDidScroll方法的实现，如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)scrollViewDidScroll:(<span class="built_in">UIScrollView</span> *)scrollView &#123;</div><div class="line">  <span class="built_in">NSArray</span> *cells = [<span class="keyword">self</span>.searchResultsTable visibleCells];</div><div class="line">  <span class="keyword">for</span> (RWTSearchResultsTableViewCell *cell <span class="keyword">in</span> cells) &#123;</div><div class="line">    <span class="built_in">CGFloat</span> value = <span class="number">-40</span> + (cell.frame.origin.y - <span class="keyword">self</span>.searchResultsTable.contentOffset.y) / <span class="number">5</span>;</div><div class="line">    [cell setParallax:value];</div><div class="line">  &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>每当列表视图滚动时，就会调用这个方法。在这个方法中，遍历所有可见的Cell，然后计算出一个偏移量，然后给每一个Cell设置一个视觉偏移。实际的偏移量将根据每一个Cell在列表视图可见部分的位置而定。</p>
<p>编译并运行程序，就可以看到一个视差效果。</p>
<p><img src="http://www.raywenderlich.com/wp-content/uploads/2014/06/ParallaxAnimation.gif" alt="5"></p>
<p>回到之前Views和ViewModels的工作。</p>
<h2 id="根据评论和点赞数查询"><a href="#根据评论和点赞数查询" class="headerlink" title="根据评论和点赞数查询"></a>根据评论和点赞数查询</h2><p>界面上应该在每一张图片的底部右侧显示评论数和点赞数。但是，当前从nib创建的文件仅仅只是显示了一个123的假数据。</p>
<p>在你使用真实数据之前，你需要在模型层添加这个功能。</p>
<p>在Model文件夹中添加一个新的继承自NSObject的类RWTFlickrPhotoMetadata，打开RWTFlickrPhotoMetadata.h添加如下代码：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>) <span class="built_in">NSUInteger</span> favorites;</div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>) <span class="built_in">NSUInteger</span> comments;</div></pre></td></tr></table></figure>
<p>打开 RWTFlickrPhotoMetadata.m实现description方法：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">- (<span class="built_in">NSString</span> *)description &#123;</div><div class="line">  <span class="keyword">return</span> [<span class="built_in">NSString</span> stringWithFormat:<span class="string">@"metadata: comments=%lU, faves=%lU"</span>,</div><div class="line">          <span class="keyword">self</span>.comments, <span class="keyword">self</span>.favorites];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>这个方法用于测试新添加的获取第一张照片的元数据的接口返回的数据是否正确。结果将被打印出来。</p>
<p>编译并运行，搜索一些照片，当结果显示时，你将看到如下log将被打印出来。</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="number">2014</span><span class="number">-06</span><span class="number">-04</span> <span class="number">07</span>:<span class="number">27</span>:<span class="number">26.813</span> RWTFlickrSearch[<span class="number">76828</span>:<span class="number">70</span>b] metadata: comments=<span class="number">120</span>, faves=<span class="number">434</span></div></pre></td></tr></table></figure>
<h2 id="取得元数据赋给可见的Cell"><a href="#取得元数据赋给可见的Cell" class="headerlink" title="取得元数据赋给可见的Cell"></a>取得元数据赋给可见的Cell</h2><p>你可以将当前的代码扩展成获取所有搜索结果的元数据。</p>
<p>但是，如果结果有100张图片，你就要调用200次API接口，每张图片两次。许多API都有一个调用频率限制，这个操作可能会导致API Key被锁定，最少也是暂时不能用。</p>
<p>其实，你只需要获取到当前在列表视图中显示的几张图片的元数据。因此，你该怎样实现这样的行为呢？你应该已经猜到了，你需要一个可以意识到他是否显示的一个ViewModel。</p>
<p>当前的RWTSearchResultsViewModel对外暴漏了一个展示在视图上的RWTFlickrPhoto数组的接口，这些模型层的对象会被保留给View。为了能够添加一个可见性的概念，你将把这些在ViewModels里的模型对象封装起来。</p>
<p>在ViewModel文件夹中添加一个NSObject的子类RWTSearchResultsItemViewModel，打开头文件，添加如下内容：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">@import</span> Foundation;</div><div class="line"><span class="meta">#import <span class="meta-string">"RWTFlickrPhoto.h"</span></span></div><div class="line"><span class="meta">#import <span class="meta-string">"RWTViewModelServices.h"</span></span></div><div class="line"></div><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">RWTSearchResultsItemViewModel</span> : <span class="title">NSObject</span></span></div><div class="line"></div><div class="line">- (<span class="keyword">instancetype</span>) initWithPhoto:(RWTFlickrPhoto *)photo services:(<span class="keyword">id</span>&lt;RWTViewModelServices&gt;)services;</div><div class="line"></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">nonatomic</span>) <span class="built_in">BOOL</span> isVisible;</div><div class="line"><span class="keyword">@property</span> (<span class="keyword">strong</span>, <span class="keyword">nonatomic</span>) <span class="built_in">NSString</span> *title;</div><div class="line"><span class="keyword">@property</span> (<span class="keyword">strong</span>, <span class="keyword">nonatomic</span>) <span class="built_in">NSURL</span> *url;</div><div class="line"><span class="keyword">@property</span> (<span class="keyword">strong</span>, <span class="keyword">nonatomic</span>) <span class="built_in">NSNumber</span> *favorites;</div><div class="line"><span class="keyword">@property</span> (<span class="keyword">strong</span>, <span class="keyword">nonatomic</span>) <span class="built_in">NSNumber</span> *comments;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
<p>如你所见，这个ViewModel封装了RWTFlickrPhoto模型对象。</p>
<p>这个ViewModel的属性混合了如下内容：</p>
<ul>
<li>对外的模型属性（title，url）</li>
<li>会动态更新的图像元数据模型（favorites，comments）</li>
<li>isVisible用来指示ViewModel是否可见或不可见</li>
</ul>
<p>打开RWTSearchResultsItemViewModel.m导入如下头文件：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">&lt;ReactiveCocoa/ReactiveCocoa.h&gt;</span></span></div><div class="line"><span class="meta">#import <span class="meta-string">&lt;ReactiveCocoa/RACEXTScope.h&gt;</span></span></div><div class="line"><span class="meta">#import <span class="meta-string">"RWTFlickrPhotoMetadata.h"</span></span></div></pre></td></tr></table></figure>
<p>然后在类扩展中添加如下私有属性：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="class"><span class="keyword">@interface</span> <span class="title">RWTSearchResultsItemViewModel</span> ()</span></div><div class="line"></div><div class="line"><span class="keyword">@property</span> (<span class="keyword">weak</span>, <span class="keyword">nonatomic</span>) <span class="keyword">id</span>&lt;RWTViewModelServices&gt; services;</div><div class="line"><span class="keyword">@property</span> (<span class="keyword">strong</span>, <span class="keyword">nonatomic</span>) RWTFlickrPhoto *photo;</div><div class="line"></div><div class="line"><span class="keyword">@end</span></div></pre></td></tr></table></figure>
<p>在同一文件中实现如下方法：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">instancetype</span>)initWithPhoto:(RWTFlickrPhoto *)photo services:(<span class="keyword">id</span>&lt;RWTViewModelServices&gt;)services &#123;</div><div class="line">  <span class="keyword">self</span> = [<span class="keyword">super</span> init];</div><div class="line">  <span class="keyword">if</span> (<span class="keyword">self</span>) &#123;</div><div class="line">    _title = photo.title;</div><div class="line">    _url = photo.url;</div><div class="line">    _services = services;</div><div class="line">    _photo = photo;</div><div class="line"></div><div class="line">    [<span class="keyword">self</span> initialize];</div><div class="line">  &#125;</div><div class="line">  <span class="keyword">return</span>  <span class="keyword">self</span>;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>然后添加一个initialize方法，注意了，这是关键的地方：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">- (<span class="keyword">void</span>)initialize &#123;</div><div class="line">  RACSignal *fetchMetadata =</div><div class="line">    [RACObserve(<span class="keyword">self</span>, isVisible)</div><div class="line">     filter:^<span class="built_in">BOOL</span>(<span class="built_in">NSNumber</span> *visible) &#123;</div><div class="line">       <span class="keyword">return</span> [visible boolValue];</div><div class="line">     &#125;];</div><div class="line"></div><div class="line">  @weakify(<span class="keyword">self</span>)</div><div class="line">  [fetchMetadata subscribeNext:^(<span class="keyword">id</span> x) &#123;</div><div class="line">    @strongify(<span class="keyword">self</span>)</div><div class="line">    [[[<span class="keyword">self</span>.services getFlickrSearchService] flickrImageMetadata:<span class="keyword">self</span>.photo.identifier]</div><div class="line">     subscribeNext:^(RWTFlickrPhotoMetadata *x) &#123;</div><div class="line">       <span class="keyword">self</span>.favorites = @(x.favorites);</div><div class="line">       <span class="keyword">self</span>.comments = @(x.comments);</div><div class="line">     &#125;];</div><div class="line">  &#125;];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>方法的第一部分创建了一个用于监听isVisible属性的信号fetchMetadate，并且根据isVisible的值进行了过滤。结果就是只有当isVisible为true时这个信号才会发出Next Value。</p>
<p>接下来一部分就是订阅这个信号以便开始请求flickrImageMetadata方法。当这个内嵌的信号触发Next时，将更新赞数和评论数。</p>
<p>总的来说，当isVisible为true时，将触发Flickr请求，然后在未来的某个点更新comments和favorites属性。</p>
<p>为了使这个新的ViewModel能够使用，打开RWTSearchResultsViewModel.m导入如下头文件：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">&lt;LinqToObjectiveC/NSArray+LinqExtensions.h&gt;</span></span></div><div class="line"><span class="meta">#import <span class="meta-string">"RWTSearchResultsItemViewModel.h"</span></span></div></pre></td></tr></table></figure>
<p>在初始化方法中，删除当前的代码，然后设置_searchResults如下：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">_searchResults =</div><div class="line">  [results.photos linq_select:^<span class="keyword">id</span>(RWTFlickrPhoto *photo) &#123;</div><div class="line">    <span class="keyword">return</span> [[RWTSearchResultsItemViewModel alloc]</div><div class="line">              initWithPhoto:photo services:services];</div><div class="line">  &#125;];</div></pre></td></tr></table></figure>
<p>这段代码将每一个模型对象封装成了一个ViewModel。</p>
<p>最后一步就是根据视图设置isVisible属性，使得这些新的属性能够生效。</p>
<p>打开RWTSearchResultsTableViewCell.m添加如下头文件：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line"><span class="meta">#import <span class="meta-string">"RWTSearchResultsItemViewModel.h"</span></span></div></pre></td></tr></table></figure>
<p>在同一文件中，改变bindViewModel方法的第一行代码，使用新添加的ViewModel。</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">RWTSearchResultsItemViewModel *photo = viewModel;</div></pre></td></tr></table></figure>
<p>在同一方法中添加如下代码：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">[RACObserve(photo, favorites) subscribeNext:^(<span class="built_in">NSNumber</span> *x) &#123;</div><div class="line">  <span class="keyword">self</span>.favouritesLabel.text = [x stringValue];</div><div class="line">  <span class="keyword">self</span>.favouritesIcon.hidden = (x == <span class="literal">nil</span>);</div><div class="line">&#125;];</div><div class="line"></div><div class="line">[RACObserve(photo, comments) subscribeNext:^(<span class="built_in">NSNumber</span> *x) &#123;</div><div class="line">  <span class="keyword">self</span>.commentsLabel.text = [x stringValue];</div><div class="line">  <span class="keyword">self</span>.commentsIcon.hidden = (x == <span class="literal">nil</span>);</div><div class="line">&#125;];</div><div class="line"></div><div class="line">photo.isVisible = <span class="literal">YES</span>;</div></pre></td></tr></table></figure>
<p>这样当comments和favorites属性发生变化时，对应的lable以及image也会更新。</p>
<p>最后一步，设置ViewModel的isVisible为YES。</p>
<h2 id="后记"><a href="#后记" class="headerlink" title="后记"></a>后记</h2><p>终于翻译完了，这是我第一次尝试翻译英文技术文章，前后断断续续用了大概两周的时间，真的很累，说实话，最后完全是为了翻译而去翻译的，而不是为了学习技术而去翻译的。不过这个过程中还是学到了不少东西。以后我还会坚持找一些经典的文章拿来翻译，不过不会翻译这么长的文章了，太累了。</p>
<p>水平有限，很多地方翻译的不是很通顺，有些句子不知道怎么翻好，干脆就没有翻译，个中错误，以后有空会慢慢纠正。（2016-5-19）</p>

      
    </div>

    <div>
      
        
      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/05/08/2016年5月开发问题记录/" rel="next" title="2016年5月开发问题记录">
                <i class="fa fa-chevron-left"></i> 2016年5月开发问题记录
              </a>
            
          </div>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/05/29/自定义NSOperation的那些事/" rel="prev" title="自定义NSOperation的那些事">
                自定义NSOperation的那些事 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2016/05/09/MVVMTutorialwithReactiveCocoaPart2(翻译)/"
           data-title="【翻译】MVVM Tutorial with ReactiveCocoa Part 2" data-url="http://yoursite.com/2016/05/09/MVVMTutorialwithReactiveCocoaPart2(翻译)/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/smallhead.png"
               alt="liujinlongxa" />
          <p class="site-author-name" itemprop="name">liujinlongxa</p>
          <p class="site-description motion-element" itemprop="description">生命永不息，Coding永不止</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">31</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/liujinlongxa" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/JaylonLiu" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1523828165/home" target="_blank" title="微博">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  微博
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.douban.com/people/2470188/" target="_blank" title="豆瓣">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  豆瓣
                </a>
              </span>
            
          
        </div>

        
        

        
        

      </section>

      
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">
            
              
            
            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#实现ViewModel导航"><span class="nav-number">1.</span> <span class="nav-text">实现ViewModel导航</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#呈现搜索结果列表"><span class="nav-number">2.</span> <span class="nav-text">呈现搜索结果列表</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#更好的Tableview数据绑定方法"><span class="nav-number">3.</span> <span class="nav-text">更好的Tableview数据绑定方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#一些UI的个性化"><span class="nav-number">4.</span> <span class="nav-text">一些UI的个性化</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#根据评论和点赞数查询"><span class="nav-number">5.</span> <span class="nav-text">根据评论和点赞数查询</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#取得元数据赋给可见的Cell"><span class="nav-number">6.</span> <span class="nav-text">取得元数据赋给可见的Cell</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#后记"><span class="nav-number">7.</span> <span class="nav-text">后记</span></a></li></ol></div>
            
          </div>
        </section>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">liujinlongxa</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.0.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.0.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.0.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"liujinlongxa"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
  






  
  
  

  

  

</body>
</html>
